<template>
  <el-card class="box-card el-card-flex addHolidayRules">
    <div slot="header" class="clearfix">
      <span>
        添加代理
      </span>
    </div>
    <div class="text item">
      <div style="margin-bottom: 50px;overflow: auto;">
        <el-form :model="formInline" ref="formInline" class="demo-form-inline">
          <el-form-item
            label="代理人:"
            label-width="82px"
            prop="agentFromNameList"
            :rules="[
              {
                required: true,
                message: '代理人不能为空',
                trigger: ['blur', 'change']
              }
            ]"
          >
            <el-col :span="5">
              <el-input clearable v-model="formInline.agentFromNameList" readonly>
                <el-button slot="append" icon="el-icon-search" @click="pleaseChoose"></el-button>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            label="代理方式:"
            prop="agentType"
            :rules="[
              {
                required: true,
                message: '请选择代理方式',
                trigger: 'blur'
              }
            ]"
          >
            <el-radio-group v-model="formInline.agentType" @change="radioChange">
              <el-radio border label="ALL">完全代理</el-radio>
              <el-radio border label="PART">部分代理</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="el-box">
            <el-form-item
              class="el-box"
              label="生效时间:"
              prop="startTime"
              :rules="[
                {
                  type: 'string',
                  required: true,
                  message: '请选择生效时间',
                  trigger: ['blur', 'change']
                }
              ]"
            >
              <el-col :span="15">
                <el-date-picker
                  type="date"
                  :picker-options='startTime'
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  v-model="formInline.startTime"
                  @blur="blur"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item
              class="el-box"
              style="margin-left: 20px;"
              label="终止时间:"
              prop="endTime"
              :rules="[
                {
                  type: 'string',
                  required: true,
                  message: '请选择终止时间',
                  trigger: ['blur', 'change']
                }
              ]"
            >
              <el-col :span="15">
                <el-date-picker
                  type="date"
                  :picker-options='endTime'
                  placeholder="选择日期时间"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  v-model="formInline.endTime"
                  @blur="blur"
                >
                </el-date-picker>
              </el-col>
            </el-form-item>
          </div>
          <el-form-item
            label="代理原因:"
            prop="agentReason"
            :rules="[
              {
                required: true,
                message: '代理原因不能为空',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="11">
              <el-input type="textarea" v-model="formInline.agentReason"></el-input>
            </el-col>
          </el-form-item>
        </el-form>
        <el-row style="text-align:right; margin-bottom:10px;">
          <el-button type="primary" plain @click="addProcess" v-show="!process">增加例外流程</el-button>
          <el-button type="primary" plain @click="addProcess" v-show="process">添加流程和活动</el-button>
        </el-row>
        <el-table
          :data="processTableData"
          border
          stripe
          style="width: 100%; margin-bottom: 50px"
          ref="agentTable"
        >
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="itemID" label="流程/活动定义ID"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="itemType" label="类型"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="itemName" label="流程/活动名称" align="center"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="accessType" label="流程操作权限" align="center">
            <template slot-scope="scope">
               <div v-if="scope.row.type == 'PROCESS' && formInline.agentType == 'PART'">
               <el-select v-model="scope.row.accessType" placeholder="全部">
                  <el-option
                    v-for="item in authorityOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div v-else>全部</div>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" sortable :show-overflow-tooltip="true" prop="parentId" label="活动所属流程定义ID" v-if="activeProcessId"></el-table-column>
          <el-table-column min-width="100px" sortable prop="control" align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button class="td-btn-icon" type="text" title="删除" icon="el-icon-delete" @click="handleDelete(scope.$index, processTableData)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="holidayFooter">
      <el-button type="primary" @click="handleAgentSave">
        保存
        <i class="el-icon-document-checked el-icon--right"></i>
      </el-button>
      <el-button type="danger" @click="handleAddClose">
        关闭
        <i class="el-icon-close"></i>
      </el-button>
    </div>
    <!-- 选择代理人 -->
    <el-dialog
      title="请选择代理人"
      :visible.sync="dialogAgentVisible"
      :before-close="handleAgentClose"
      class="demo-ruleForm"
      custom-class="el-dialog-flex"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-input clearable v-model="textSearchAgent" placeholder="请输入用户名/别名" style="width:280px;" @keyup.enter.native="agentPeopleEvent" @clear="agentPeopleEvent">
        <el-button slot="append" icon="el-icon-search" @click="agentPeopleEvent"></el-button>
      </el-input>
      <el-table
          :data="agentPeopleData"
          border
          stripe
          @selection-change="handleSelectionChange"
          style="width: 100%;margin: 10px 0;"
          ref="agentTable"
          height="100%"
          >
          <el-table-column type="selection" align="center"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="userName" label="用户名称"></el-table-column>
          <el-table-column min-width="100px" sortable :show-overflow-tooltip="true" prop="name" label="员工姓名"></el-table-column>
        </el-table>
        <!-- 分页 -->
				<el-pagination
					background
					@size-change="handleSizeAgentChange"
					:current-page="currentAgentPage"
					@current-change="handleCurrentAgentChange"
					:page-size="pageAgentSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="totalAgent"
        ></el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAgentSubmit">
          确定
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button @click="handleAgentCloseCheck">
          取消
          <i class="el-icon-refresh-left"></i>
        </el-button>
      </span>
    </el-dialog>
    <!-- 添加流程 -->
    <el-drawer
      title="添加流程"
      :before-close="handleProcessClose"
      :visible.sync="dialogProcessVisible"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      :wrapperClosable="false"
      :close-on-press-escape="false"
      >
      <div class="demo-drawer__content el-box-column" style="height: 100%; margin-left: 18px;">
        <div class="el-flex">
          <el-tree
            :props="propsProcessTree"
            :load="loadNodeGetProcessTree"
            lazy
            :check-on-click-node="true"
            ref="treeProcess"
            node-key="id"
            show-checkbox
            :key="treeKey"
            @check="handleProcessCheck">
          </el-tree>
        </div>
        <div class="demo-drawer__footer" style="text-align: right; margin-bottom: 10px; padding-right:10px;">
          <el-button type="primary" @click="handleProcessTrue">
            确定
            <i class="el-icon-document-checked el-icon--right"></i>
          </el-button>
          <el-button @click="handleProcessCancel">
            取消
            <i class="el-icon-refresh-left"></i>
          </el-button>
        </div>
      </div>
    </el-drawer>
  </el-card>
</template>
<script>
import { Tree, Dialog, Table, TableColumn, Pagination, MessageBox, Message, Drawer, DatePicker} from 'element-ui'
import { userList } from '@/api/authority/areaManage/areaManage.js'
import { deleteAgentItem, workFlowProxyInsert } from '@/api/workflow/holidayRules/holidayRules.js'
import { workflowGetProcessTree, workflowGetProcessCatalog, workflowGetProcessProcess } from '@/api/workflow/processAuthority/processAuthority.js'
export default {
  name: 'addHolidayRules',
  components: {
    'el-tree': Tree, // 树形菜单
		'el-dialog': Dialog, // 对话框
		'el-table': Table, // 表格
		'el-table-column': TableColumn, // 表格列
		'el-pagination': Pagination, // 分页
    'el-drawer': Drawer, // 抽屉
    'el-date-picker': DatePicker
  },
  data() {
    let holidayRulesVal = {
      agentToList: [],
      agentType: '',
      startTime: '',
      endTime: '',
      agentReason: '',
      agentItemList: []
    }
    return {
      holidayRulesVal: JSON.parse(JSON.stringify(holidayRulesVal)), // 用于重置表单
      processData: [],
      formInline: JSON.parse(JSON.stringify(holidayRulesVal)),
      dialogAgentVisible: false, // 选择代理人弹框是否显示
      checkDatas: [], // 选择代理人选中行数据
      textSearchAgent: '', // 搜索内容
      totalAgent: 0, // 总条数
      currentAgentPage: 1, // 当前显示页
      pageAgentSize: 20, // 每页显示条数
      dialogProcessVisible: false, // 添加流程弹框是否显示
      propsProcessTree: {
        label: 'name',
        isLeaf: 'leaf',
        disabled: this.disabledFn
      },
      process: '', // 点击完全或者部分代理显示不同按钮
      activeProcessId: false, // 默认活动所属流程定义ID没有
      agentPeopleData: [], // 获取所有代理人数据
      processTableData: [], // 流程活动数据
      treeCheckData: [], // 选中着的tree的数据
      treeKey: 1, // 自动刷新树
      authorityOptions: [
        {
          value: 'ALL',
          label: '全部'
        },
        {
          value: 'STARTPROC',
          label: '启动流程'
        },
        {
          value: 'EXEWI',
          label: '执行工作项'
        }
      ],
      //生效时间不能早于今天
      startTime: {
        disabledDate: time => {
          if (this.formInline.endTime) {
            return (
              time.getTime() > new Date(this.formInline.endTime).getTime() // 不能选择的时间值
            )
          }
        }
      },
      // 失效时间不能早于生效时间
      endTime: {
        disabledDate: time => {
          if (this.formInline.startTime){
            return (
              time.getTime() < new Date(this.formInline.startTime).getTime() - 8.64e7 // 加- 8.64e7则表示包当天
            )
          } 
        }
      }
    }
  },
  created() {
    this.getTime() // 计算时间
    window.onresize = () => {
      this.$refs.agentTable.doLayout() //监听窗口变化，重绘表格布局
    }
  },
  methods: {
    //获取本地当前时间
    getTime() {
      var date = new Date()
      var year =  date.getFullYear()
      var month =  date.getMonth()+1
      var strDate =  date.getDate()
      if (month >= 1 && month <= 9) {
        month = "0" + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate
      }
    },
    //计算两个时间段中间有多少天
    blur () {
      var star = this.formInline.startTime
      var end = this.formInline.endTime
      var date1 = new Date(star)
      var date2 = new Date(end)
      var date = (date2.getTime()-date1.getTime())/(1000*60*60*24)+1 //不用考虑闰年否
    },
    // 改变radio触发事件
    radioChange (val) {
      if (val == 'ALL') {
        if (!this.processTableData || !this.processTableData.length || !Array.isArray(this.processTableData)) {
          this.process = false
          this.activeProcessId = false
        } else {
          MessageBox.confirm('是否要放弃添加流程和活动?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.process = false
          this.activeProcessId = false
          this.processTableData = []
        })
        .catch(() => {})
        }
      } else {
        if (!this.processTableData || !this.processTableData.length || !Array.isArray(this.processTableData)) {
          this.process = true
          this.activeProcessId = true
        } else {
          MessageBox.confirm('是否要放弃增加例外流程?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.process = true
          this.activeProcessId = true
          this.processTableData = []
        })
        .catch(() => {})
        }
      }
    },
    // 删除事件
    handleDelete (index, data) {
      console.log(data)
      MessageBox.confirm('是否确定要删除该行数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        let agentItemID = data[index].agentItemID
        if (!agentItemID) {
          data.splice(index, 1)
          return
        }
        deleteAgentItem([agentItemID]).then(res => {
          if (res.data.code === 10000) {
            Message.success('删除成功')
            data.splice(index, 1)
          }
        })
      })
      .catch(() => {})
    },
    // 保存按钮
    handleAgentSave () {
      this.$refs.formInline.validate(valid => {
        if (!valid) return false
          workFlowProxyInsert({
            "agentToList": this.formInline.agentToList,
            "agentType": this.formInline.agentType,
            "startTime": this.formInline.startTime,
            "endTime": this.formInline.endTime,
            "agentReason": this.formInline.agentReason,
            "agentItemList": this.processTableData
         }).then(res => {
          console.log(res)
          if (res.data.code === 10000) {
            Message.success('保存成功')
            this.handleAddClose()
          }
        })
      })
    },
    // 关闭按钮
    handleAddClose () {
      this.$router.go(-1) // 返回上一页
    },
    // 选择代理人
    pleaseChoose () {
      this.dialogAgentVisible = true
      this.agentPeopleEvent()
    },
    // 点击选着代理人是之前选的数据默认选中
    toggleRowSelection (arr = []) {
      if (!arr || !arr.length || !Array.isArray(arr)) return
      arr.forEach(e => {
        this.agentPeopleData.forEach(row => {
          console.log(row)
          if (row.name === e.name) {
            this.$refs.agentTable.toggleRowSelection(row, true)
          }
        })
      })
    },
    // 选择代理人点击复选框
    handleSelectionChange (val) {
      this.checkDatas = val
      this.checkDatas.forEach((e, index) => {
        let tempObj = {}
        tempObj.id = e.userAccountId
        // tempObj.code = e.userName
        tempObj.name = e.name
        // tempObj.type = 'emp'
        this.checkDatas[index] = tempObj
      })
      console.log(this.checkDatas)
    },
    // 选择代理人弹框里分页里每页数据
    handleSizeAgentChange (val) {
      this.pageAgentSize = val
      this.agentPeopleEvent()
    },
    // 选择代理人组弹框里分页里当前页数
    handleCurrentAgentChange (val) {
      this.currentAgentPage = val
      this.agentPeopleEvent()
    },
    // 关闭选择代理人弹窗
    handleAgentClose () {
      this.dialogAgentVisible = false
    },
    // 点击选择代理人确定按钮
    handleAgentSubmit () {
      this.setAgentFormName(this.checkDatas)
      this.handleAgentClose()
    },
    // 给this.formInline对象新增agentFromNameList属性
    setAgentFormName(arr = []) {
      this.$set(this.formInline, 'agentToList', arr)
      if (arr.length) {
        let nameArr = []
        arr.forEach(e => {
          console.log(e)
          nameArr.push(e.name)
          this.$set(this.formInline, 'agentFromNameList', nameArr.join(', '))
          // console.log(this.formInline)
        })
      } else {
        this.$set(this.formInline, 'agentFromNameList', '')
      }
    },
    // 点击选择代理人取消按钮
    handleAgentCloseCheck () {
      this.handleAgentClose()
    },
    //disabled函数
    disabledFn (data, node) {
      // console.log("disabled函数: ", data, node)
      if (data.type == "CATALOG") {  // 根据自己的节点数据条件设置判断
        return true
      } else {
        return false
      }
    },
    // 获取添加流程树形结构数据
    loadNodeGetProcessTree (node, resolve) {
      console.log(node)
      if (node.level === 0) {
        workflowGetProcessTree().then(res => {
          console.log(res)
          if (res.data.code === 10000) {
            let processCatalogTreeData = res.data.data.processTree
            if (this.formInline.agentType === 'ALL') processCatalogTreeData = processCatalogTreeData.filter(v => v.type !== 'ACTIVITY')
            resolve(processCatalogTreeData)
          }
        }).catch(res => {
          resolve([])
        })
      } else {
        if (node.data.type == 'CATALOG') { // 目录
          console.log(node.data.type)
          let parentCatalogId = node.data.id
          workflowGetProcessCatalog(parentCatalogId).then(res => {
            console.log(res)
            if (res.data.code === 10000) {
              let catalogTreeData = res.data.data.processTree
              if (this.formInline.agentType === 'ALL') catalogTreeData = catalogTreeData.filter(v => v.type !== 'ACTIVITY')
              resolve(catalogTreeData)
            }
          }).catch(res => {
            resolve([])
          })
        } else if (node.data.type == 'PROCESS') { // 流程
          // this.expand-on-click-node = false
          let processId = node.data.id
          workflowGetProcessProcess(processId).then(res => {
            console.log(res)
            if (res.data.code === 10000) {
              let processData = res.data.data.processTree
              if (this.formInline.agentType === 'ALL') processData = processData.filter(v => v.type !== 'ACTIVITY')
              resolve(processData)
            }
          }).catch(res => {
            resolve([])
          })
        } else {
          return resolve([])
        }
      }
    },
    // 当树结构的复选框被点击的时候触发事件
    handleProcessCheck (data, checked, indeterminate) {
      // console.log(checked)
      let treeCheckData = checked.checkedNodes // 选中着的tree的数据
      // if (treeCheckData.length >= 2) {
      //   let firstData = treeCheckData[0] // 当前点击的前一个对象
      //   let lastData = treeCheckData[treeCheckData.length - 1] // 最新点击的对象
      //   if (firstData.type !== lastData.type) { // 如果之前选中的对象的type不等于刚刚点击的这个对象的type,说明类型不一样了
      //     treeCheckData = [lastData]
      //   }
      // }
      // this.$refs.treeProcess.setCheckedNodes(treeCheckData)
      this.treeCheckData = treeCheckData
      console.log(this.treeCheckData)
    },
    // 点击添加流程事件
    addProcess () {
      this.dialogProcessVisible = true
      // setTimeout(() => {
      //   let tempProcessId = []
      //   this.treeCheckData = this.processTableData || []
      //   this.processTableData.forEach(e => {
      //     tempProcessId.push(e.id)
      //     this.$refs.treeProcess.setCheckedKeys(tempProcessId)
      //   })
      // }, 0)
    },
    // 确定添加流程弹框
    handleProcessTrue () {
      // 表格里面,没有数据,直接复制等于即可
      if (!this.treeCheckData.length) { // 未选中任何节点
        Message.warning('您还未选择流程或节点哦')
        return
      }
      let treeCheckDataC = this.$refs.treeProcess.getCheckedNodes() // 获取所有勾选的数据
      let pros = [] // 存储流程的id
      let proArr = []// 存储选中的流程数据
      treeCheckDataC.forEach(e => {
        if(e.type == "PROCESS"){
          pros.push(e.id)
          proArr.push(e)
        }
      })
      treeCheckDataC.forEach(e => {
        if(e.activityParentId){//如果是活动节点
          let aInd = pros.indexOf(String(e.activityParentId))
          if(aInd == -1){//如果不存在活动节点的父节点(流程节点)
            proArr.push(e)
          }
        }
      })
      this.treeCheckData = proArr
      console.log(this.treeCheckData)
      // 表格有数据
      if (this.processTableData.length) {
        MessageBox.confirm('您当前选择的流程或节点与已选择的流程或节点有冲突,是否自动解决冲突?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
        .then(() => {
          let itemIDs = [] // 表格ID数组
          let parentIds = []// 
          this.processTableData.forEach(e => {
            itemIDs.push(e.itemID)
            parentIds.push(e.parentId)
          })
          this.treeCheckData.forEach(e => {
            let idI= itemIDs.indexOf(e.id)
            if(e.activityParentId){// 如果是活动节点
              if ( idI != -1 && pIdI != -1) { // 自身去重,如果活动ID和所属流程ID同时重复,则移除
                this.processTableData.splice(idI,1)
              }
              let pIdI= itemIDs.indexOf(e.activityParentId)
              if ( pIdI != -1) { // 如果表格上有属于已选活动的流程,则移除
                this.processTableData.splice(pIdI,1)
              }
            } else { // 如果是流程节点
                if ( idI != -1) { // 自身去重,如果流程ID重复,则移除
                  this.processTableData.splice(idI,1)
                }
                let proId = e.id // 流程id
                // 如果表格上有属于已选流程的活动(可能会有多个),则移除
                for(let i = parentIds.length-1; i >= 0; i--){
                  if (parentIds[i] == proId) {
                    this.processTableData.splice(i,1)
                  }
                }
                // parentIds.forEach((e,i)=>{
                //   if(e == proId){
                //     this.processTableData.splice(i,1)
                //   }
                // })
                console.log(this.processTableData)
              // let parIdI = parentIds.indexOf(e.id)
              // if ( parIdI != -1) { // 如果表格上有属于已选流程的活动,则移除
              //   this.processTableData.splice(parIdI,1)
              // }
            }
            
              e.itemID = e.id
              e.itemType = e.type
              e.itemName = e.name
              e.parentId = e.activityParentId
              if (this.formInline.agentType == 'ALL') {
                e.accessType = 'ALL'
              }
              e.agentItemID = ''
              this.processTableData.push(e)
            })
            this.handleProcessClose() // 关闭
          })
          .catch(() => {})
        } else { // 表格无数据
          this.treeCheckData.forEach(e => {
            e.itemID = e.id
            e.itemType = e.type
            e.itemName = e.name
            e.parentId = e.activityParentId
            if (this.formInline.agentType == 'ALL') {
              e.accessType = 'ALL'
            }
            e.agentItemID = ''
            this.processTableData.push(e)
        })
        this.handleProcessClose() // 关闭
      }
    },
    // 取消添加流程弹框
    handleProcessCancel () {
      this.handleProcessClose()
    },
    // 关闭添加流程弹框
    handleProcessClose () {
      this.dialogProcessVisible = false
      this.treeKey += 1
    },
    // 获取所有代理人数据事件
    agentPeopleEvent() {
      let data = {
        // page: this.currentAgentPage,
        // size: this.pageAgentSize
      }
      data.type = 1
      data.userName = this.textSearchAgent
      data.name = this.textSearchAgent
      userList({
				params: data
			}).then(res => {
        // console.log(res)
        this.agentPeopleData = res.data.data.records
        this.totalAgent = res.data.data.total
        setTimeout(() => {
          this.toggleRowSelection(this.formInline.agentToList)
					this.$refs.agentTable.doLayout() // 表格刷新以后，重绘表格宽度
				}, 0)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.addHolidayRules{
	position: relative;
	.holidayFooter {
		position: absolute;
		bottom: 10px;
		right: 20px;
		width: 100%;
		height: 45px;
		line-height: 45px;
		text-align: right;
		background: #ffffff;
    z-index: 999;
  }
}
</style>


